package com.cmccgz.udacs_landlord_webapp.jpush;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import com.cicadamob.contact.api.Utils.StringUtil;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.ApiService;
import com.cmccgz.udacs_landlord_webapp.bean.AccreditDetailBean;
import com.cmccgz.udacs_landlord_webapp.bean.ResultBean;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import rx.Subscriber;

/**
 * Created by June on 2017-8-18.
 */

public class AccreditPresenter implements AccreditContract.Presenter {

    private AccreditContract.View mContentView;
    public static final int TYPE_START = 1;  //开始时间
    public static final int TYPE_END = 2;  //结束时间
    String[] times = {"无限次", "1次", "2次", "3次", "4次", "5次"};

    AccreditPresenter(AccreditContract.View contentView) {
        this.mContentView = contentView;
        this.mContentView.setPresenter(this);
    }

    @Override
    public void getAccreditDetail(String mobile, String requestId) {
        ApiService.getRequestDetail(mobile, requestId).subscribe(new Subscriber<ResultBean<AccreditDetailBean>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                mContentView.requestFail("请求错误，请稍后再试");
            }

            @Override
            public void onNext(ResultBean<AccreditDetailBean> resultBean) {
                if ("0".equals(resultBean.rsmsg.rscode)) {
                    AccreditDetailBean detailBean = resultBean.resp;
                    boolean has_use = detailBean.getHas_use();
                    String type = detailBean.getType();
                    String v_name = detailBean.getV_name();
                    String v_mobile = detailBean.getV_mobile();
                    String request_time = detailBean.getRequest_time();
                    String device_name = detailBean.getDevice_name();
                    String device_image = detailBean.getDevice_image();
                    String device_address = detailBean.getDevice_address();
                    String remark = detailBean.getRemark();
                    List<AccreditDetailBean.DevicesBean> deviceList = detailBean.getDevices();
                    mContentView.showAccreditInfo(v_name, v_mobile, request_time, device_name, remark, deviceList);
                    if (has_use) {
                        mContentView.wasHandled();
                    }
                }else{
                    mContentView.requestFail(resultBean.rsmsg.rsdesc);
                }
            }
        });
    }

    @Override
    public void handleAccredit(String requestId, String isAgree, String reason, String deviceId, String startTime, String endTime, String times) {
        mContentView.showLoadingDialog();
        ApiService.handleVisitorRequest(requestId, isAgree, reason, deviceId, startTime, endTime, times).subscribe(new Subscriber<ResultBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                mContentView.requestFail("请求错误，请稍后再试");
            }

            @Override
            public void onNext(ResultBean resultBean) {
                if ("0".equals(resultBean.rsmsg.rscode)) {
                    mContentView.handleSuccess();
                } else {
                    mContentView.handleFail();
                }
            }
        });
    }

    @Override
    public void selectDevice(Context context, final String[] devicesId, final String[] devicesAddress) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("选择门禁");
        builder.setItems(devicesAddress, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.out.println("第" + which + "个");
                String deviceId = devicesId[which];
                String deviceName = devicesAddress[which];
                mContentView.setDevice(deviceId, deviceName);
            }
        });
        builder.show();
    }

    @Override
    public void selectDateTime(Context context, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = View.inflate(context, R.layout.date_time_dialog, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        final TimePicker timePicker = (android.widget.TimePicker) view.findViewById(R.id.time_picker);
        builder.setTitle(type == TYPE_START ? "选择开始时间" : "选择结束时间");
        builder.setView(view);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);
        timePicker.setIs24HourView(true);
        timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(Calendar.MINUTE);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d-%d-%d", datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth()));
                sb.append(" ");
                sb.append(timePicker.getCurrentHour()).append(":").append(timePicker.getCurrentMinute());
                switch (type) {
                    case TYPE_START:
                        mContentView.setStartTime(sb.toString());
                        break;
                    case TYPE_END:
                        mContentView.setEndTime(sb.toString());
                        break;
                    default:
                        break;
                }
                dialog.cancel();
            }

        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        Dialog dialog = builder.create();
        dialog.show();
    }

    @Override
    public void selectTimes(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("选择限制次数");
        builder.setItems(times, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.out.println("第" + which + "个");
                String name = times[which];
                mContentView.setTimes(which);
            }
        });
        builder.show();
    }

    @Override
    public void refuseBox(final Context context, final String requestId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = View.inflate(context, R.layout.edittext_dialog, null);
        final EditText et_reason = (EditText) view.findViewById(R.id.et_reason);
        builder.setTitle("输入拒绝理由");
        builder.setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String content = et_reason.getText().toString();
                if (StringUtil.isEmpty(content)) {
                    ToastUtils.show(context, "拒绝理由不能为空");
                    return;
                }
                if (StringUtil.isEmpty(requestId)) {
                    ToastUtils.show(context, "REQUEST_Id IS NULL");
                    return;
                }
                handleAccredit(requestId, "false", content, "", "", "", "");
                dialog.cancel();
            }

        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        Dialog dialog = builder.create();
        dialog.show();
    }

    @Override
    public void selectDefaultTime() {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        String startTime = dft.format(cal.getTime());
        cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 4);
        String endTime = dft.format(cal.getTime());
        mContentView.setDefaultTime(startTime, endTime);
    }

    @Override
    public void start() {

    }

}
